//
//  CHSearchView.swift
//  nurseApp
//
//  Created by cyptt on 2022/7/12.
//

import UIKit
public enum CHSearchStyle : Int {
    
    case left = 0    //左边 默认左边
    case center = 1  //中间
    case right = 2   //右边
}

public class CHSearchView: UIView,UITextFieldDelegate {
    
    
    public var paddingLR:CGFloat = 12 //距离左边/右边的距离
    public  var isShowSearchIcon:Bool  = true //是否现在搜索按钮默认显示
    public var isShowRightBtn:Bool = false // 是否显示右边按钮 true 显示 默认不显示
    public var isShowChaBtn:Bool = true   //是否显示右边叉叉按钮 true 显示 默认显示
    
    private var searchStyle:CHSearchStyle = .left
    private let textFont:UIFont = UIFont.systemFont(ofSize: 14) //默认字体
    private var iconImageW:CGFloat = 17  //默认搜索图片大小17
    private var iconImageH:CGFloat = 17 //默认搜索图片大小17
    
    private var rightBtnIconW:CGFloat = 17.5  //右边按钮宽
    private var rightBtnIconH:CGFloat = 17.5  //右边按钮宽
    /*
     点击了 键盘 完成按钮
     */
    private var clickKeyBordSearchCallback:((_ text:String) -> ())?
    
    /*
     左边view
     */
    private var leftView:UIView?
    
    /*
     点击了右边的按钮按钮
     */
    private var clickRightSearchCallback:((_ text:String) -> ())?
    
    public init(style:CHSearchStyle){
        super.init(frame: CGRect.zero)
        self.searchStyle = style
        self.setUI()
    }
    
    /*
     设置字体
     */
    public func setTextFont(font:UIFont){
        self.searchTextF.font = font
    }
    
    
    /*
     设置搜索按钮图片
     */
    public func setSearchImage(img:UIImage?){
        self.searchIconImageV.image = img
    }
    
    /*
     设置图片大小
     */
    public func setSearchImageSize(size:CGSize){
        self.iconImageW = size.width
        self.iconImageH = size.height
    }
    
    /*
     设置左右间距
     */
    public func setPaddingWith(w:CGFloat){
        self.paddingLR = w
    }
    
    /*
     设置叉图片
     */
    public func setChaImage(img:UIImage?){
        self.chaBtn.setImage(img, for: UIControl.State.normal)
    }
    
    
    
    /*
     设置右边按钮图片大小
     */
    public func setRightBtnSize(size:CGSize){
        self.rightBtnIconW = size.width
        self.rightBtnIconH = size.height
    }
    
    /*
     点击了键盘搜索按钮
     */
    public func setClickKeyBordSearchCallback(closure:@escaping(_ text:String)-> ()){
        
        self.clickKeyBordSearchCallback = closure
    }
    
    /*
     点击了右边的按钮
     */
    public func setRightSearchCallback(closure:@escaping(_ text:String)-> ()){
        
        self.clickRightSearchCallback = closure
    }
    
    
    /*
     设置左边view
     */
    public func setLeftView(leftV:UIView){
        self.leftView = leftV
    }
    
    override init(frame: CGRect){
        super.init(frame: frame)
        self.setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        let selfH = self.frame.size.height
        let selfW = self.frame.size.width
        self.contentV.frame = CGRect.init(x: 0, y: 0, width: selfW, height: selfH)
        self.searchTextF.frame = CGRect.init(x: 0, y: 0, width: selfW, height: selfH)
        self.searchIconImageV.frame = CGRect.init(x:0, y: 0, width: self.iconImageW, height: self.iconImageH)
        
        
        var iconImageW = self.searchIconImageV.frame.size.width
        var iconMargin:CGFloat = 10 //搜索图标距离文字距离
        if self.isShowSearchIcon == false{
            iconImageW = 0
            iconMargin = 0
            self.searchIconImageV.isHidden = true
        }else{
            iconImageW = self.searchIconImageV.frame.size.width
            iconMargin = 10
            self.searchIconImageV.isHidden = false
        }
        
        //计算展位图长度
        let palceW = self.searchTextF.placeHWidth()
        
        let iconAndMarginW = iconImageW + iconMargin
        
        print(palceW)
        if searchStyle == .left {
            
            self.searchIconImageV.center = CGPoint.init(x: paddingLR + iconImageW/2 , y: self.contentV.center.y)
            var leftV = UIView.init(frame: CGRect.init(x: 0 , y: 0, width: paddingLR + iconImageW + iconMargin, height: selfH))
            if self.leftView != nil {
                leftV = self.leftView!
            }
            self.searchTextF.leftView = leftV
            self.searchTextF.leftViewMode = UITextField.ViewMode.always
            
            self.searchTextF.textAlignment = NSTextAlignment.left
            
        }else if(searchStyle == .center){
            self.searchIconImageV.center = CGPoint.init(x:  self.contentV.center.x - (palceW )/2 , y: self.contentV.center.y)
            self.searchTextF.textAlignment = NSTextAlignment.center
            
            self.searchTextF.center = CGPoint.init(x:  self.contentV.center.x + iconAndMarginW/2 , y: self.contentV.center.y)
        }else if(searchStyle == .right){
            self.searchTextF.textAlignment = NSTextAlignment.right
            
            let rightV = UIView.init(frame: CGRect.init(x: 0 , y: 0, width: paddingLR + iconImageW + iconMargin, height: selfH))
            self.searchTextF.rightViewMode = UITextField.ViewMode.always
            self.searchTextF.rightView = rightV
            
            self.searchIconImageV.center = CGPoint.init(x: selfW - (iconMargin + iconImageW + paddingLR)/2  , y: self.contentV.center.y)
        }
        
        
        //右边的按钮
        
        let rightBtnIconWH:CGFloat = rightBtnIconW
        if ( searchStyle == .left || searchStyle == .center) && self.isShowRightBtn == true {
            
            
            self.rightBtn.frame = CGRect.init(x:0, y: 0, width: rightBtnIconWH, height: self.rightBtnIconH)
            
            self.rightBtn.center = CGPoint.init(x: selfW - rightBtnIconWH/2 - paddingLR  , y: self.contentV.center.y)
        }
        
        //右边的叉叉
        
        let chaIconMargin:CGFloat = 10
        if ( searchStyle == .left || searchStyle == .center) && self.isShowChaBtn == true{
            let rightIconWH:CGFloat = 10
            self.chaBtn.frame = CGRect.init(x:0, y: 0, width: rightIconWH, height: rightIconWH)
            if self.isShowRightBtn == true{
                
                self.chaBtn.center = CGPoint.init(x: selfW - rightIconWH/2 - paddingLR - chaIconMargin - rightBtnIconWH , y: self.contentV.center.y)
            }else{
                
                self.chaBtn.center = CGPoint.init(x: selfW - rightIconWH/2 - paddingLR, y: self.contentV.center.y)
            }
        }
    }
    func setUI(){
        self.addSubview(self.contentV)
        self.contentV.addSubview(self.searchTextF)
        
        self.contentV.addSubview(self.searchIconImageV)
        
        if ( searchStyle == .left || searchStyle == .center)   {
            self.contentV.addSubview(self.rightBtn)
            self.contentV.addSubview(self.chaBtn)
        }
    }
    
    lazy var contentV = {()->UIView in
        let v = UIView.init()
        return v
    }()
    public lazy var searchTextF = {()->UITextField in
        
        let v = UITextField.init()
        v.placeholder = "搜索"
        v.delegate = self
        v.returnKeyType = .search
        v.font = textFont
        v.textAlignment = NSTextAlignment.left //默认左边
        return v
    }()
    
    
    public lazy var searchIconImageV = {()->UIImageView in
        let v = UIImageView.init()
   
        v.image = UIImage.init(named: "search_icon", in: CHBundle.bundle(), compatibleWith: nil)
        
        return v
    }()
    
    public  lazy var rightBtn = {()->MyClickEdgeInsetsButton in
        let btn = MyClickEdgeInsetsButton.init(type: .custom)
    
        let image:UIImage? = UIImage.init(named: "search_icon", in: CHBundle.bundle(), compatibleWith: nil)
        btn.setImage(image, for: UIControl.State.normal)
        btn.addTarget(self, action: #selector(btnClick(btn: )), for: .touchUpInside)
        return btn
    }()
    
    public  lazy var chaBtn = {()->MyClickEdgeInsetsButton in
        let btn = MyClickEdgeInsetsButton.init(type: .custom)
        let image:UIImage? =  UIImage.init(named: "gray_cha_icon", in: CHBundle.bundle(), compatibleWith: nil)

        btn.isHidden = true
        btn.setImage(image, for: UIControl.State.normal)
        btn.addTarget(self, action: #selector(chaBtnClick(btn: )), for: .touchUpInside)
        return btn
        
    }()
}

// func
extension CHSearchView {
    
    /*
     右边按钮
     */
    @objc func btnClick(btn:UIButton){
        print("点击了btn")
        if self.searchTextF.text != "" {
            self.endEditing(true)
        }
        if self.clickRightSearchCallback != nil{
            self.clickRightSearchCallback!(self.searchTextF.text!)
        }
        
    }
    
    /*
     叉按钮
     */
    @objc func chaBtnClick(btn:UIButton){
        print("点击了cha")
        
        
        if self.searchTextF.text != "" {
            self.endEditing(true)
        }
        
        
        
        
        self.searchTextF.text = ""
        self.chaBtn.isHidden = true
    }
    /*
     修改中心搜索框位置
     */
    func centerClickChange(){
        let selfH = self.frame.size.height
        let selfW = self.frame.size.width
        self.contentV.frame = CGRect.init(x: 0, y: 0, width: selfW, height: selfH)
        self.searchTextF.frame = CGRect.init(x: 0, y: 0, width: selfW, height: selfH)
        self.searchIconImageV.frame = CGRect.init(x:0, y: 0, width: iconImageW, height: iconImageW)
        print(self.searchIconImageV.center)
        
        var iconImageW = self.searchIconImageV.frame.size.width
        var iconMargin:CGFloat = 10 //搜索图标距离文字距离
        if self.isShowSearchIcon == false{
            iconImageW = 0
            iconMargin = 0
            self.searchIconImageV.isHidden = true
        }else{
            iconImageW = self.searchIconImageV.frame.size.width
            iconMargin = 10
            self.searchIconImageV.isHidden = false
        }
        
        self.searchIconImageV.center = CGPoint.init(x: self.paddingLR + iconImageW/2 , y: self.contentV.center.y)
        let leftV = UIView.init(frame: CGRect.init(x: 0 , y: 0, width: self.paddingLR + iconImageW + iconMargin, height: selfH))
        
        self.searchTextF.leftView = leftV
        self.searchTextF.leftViewMode = UITextField.ViewMode.always
        self.searchTextF.textAlignment = NSTextAlignment.left
    }
}
//--UITextFieldDelegate
extension CHSearchView{
    
    public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        
        
        if searchStyle == .center {
            self.centerClickChange()
        }
        //如果是中间
        return true
    }
    public  func textFieldDidBeginEditing(_ textField: UITextField) {
        
    }
    public func textFieldDidEndEditing(_ textField: UITextField) {
        
        if self.clickKeyBordSearchCallback != nil {
            self.clickKeyBordSearchCallback!(textField.text!)
        }
    }
    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        
        let range1 = NSRange.init(location: 0, length: 1)
        
        if textField.text != "" && self.isShowChaBtn{
            self.chaBtn.isHidden = false
        }
        if range == range1{
            //最后一个
            self.chaBtn.isHidden = true
        }
        
        return true
        
    }
    
    public func textFieldShouldClear(_ textField: UITextField) -> Bool {
        
        
        return true
    }
    public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.endEditing(true)
        
        return true
    }
}


private extension UITextField{
    /*
     计算label 宽度
     */
    func placeHWidth()->CGFloat{
        let dic = [NSAttributedString.Key.font : self.font]
        let size = CGSize(width: CGFloat(MAXFLOAT), height: self.frame.size.height)
        let rect = self.placeholder!.boundingRect(with: size, options: [.usesFontLeading,.usesLineFragmentOrigin], attributes: dic as [NSAttributedString.Key : Any], context: nil)
        return CGFloat(ceilf(Float(rect.size.width)))
    }
    
    
}

//扩展小按钮点击范围
public class MyClickEdgeInsetsButton: UIButton {
    
    
    public override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        var bounds = self.bounds
        let edgeIndets = UIEdgeInsets.init(top: -20, left: -20, bottom: -20, right: -20)
        bounds = bounds.inset(by: edgeIndets)
        return bounds.contains(point)
        
    }
    
}

